package zFactory;

import mS.Data;
import node2.CriticalSection;
import node2.Node2Factory;

import org.eclipse.emf.common.util.ECollections;
import org.eclipse.emf.common.util.EList;

import srl90a01.Srl90a01;
import srl90a01.Srl90a01Factory;
import utils.PriorityComparator;
import genArchi.Node;

public class NodeSrl90a01 implements NodeInterface {

	/**
	 * Attributes
	 */
	private EList<Data> l_data;
	private EList<mS.Task> l_tasks;
	private boolean enableCreate;

	/**
	 * Constructor
	 */
	public NodeSrl90a01(EList<Data> l_data, EList<mS.Task> l_tasks, boolean enableCreate) 
	{
		this.l_data = l_data;
		this.l_tasks = l_tasks;
		this.enableCreate = enableCreate;
	}

	@Override
	public Node createNode() {
		Srl90a01 pip = Srl90a01Factory.eINSTANCE.createSrl90a01();

		/**/
		for (Data d : l_data)
		{
			node2.Data data = Node2Factory.eINSTANCE.createData();
			data.setId(d.getId());
			pip.getData().add(data);
		}

		/**/
		for (mS.Task task : l_tasks)
		{
			/* Create a new Task for the srl90a01 model and set the priority*/
			node2.Task pipTask = Node2Factory.eINSTANCE.createTask();
			pipTask.setPriority(task.getPriority());

			/* Loop on each subtasks of the task*/
			for (mS.SubTask subTask : task.getSubTasks())
			{
				/* Loop on each data resource linked to the subtask*/
				for (mS.Data subTaskData: subTask.getData())
				{
					/* Check if a critical section linked to this data resource is exists and update the exectution time*/
					boolean exists = false;
					for (CriticalSection cs : pipTask.getCriticalSections())
					{
						if (cs.getData().getId().equals(subTaskData.getId()))
						{
							exists = true;
							if (subTask.getWcet() > cs.getExecutionTime()) cs.setExecutionTime(subTask.getWcet());
						}
					}

					/* The critical section does not exist and must be created */
					if (!exists)
					{
						/* Create the Critical Section and set the execution time*/
						node2.CriticalSection newCS = Node2Factory.eINSTANCE.createCriticalSection();
						newCS.setExecutionTime(subTask.getWcet());

						/* Look for the index of the corresponding data*/
						int i = 0;
						while(!pip.getData().get(i).getId().equals(subTaskData.getId()))
						{
							i++;
						}

						/* Set the data to the critical section*/
						newCS.setData(pip.getData().get(i));
						newCS.setTask(pipTask);
						pip.getData().get(i).getCriticalSections().add(newCS);
						/* Add the critical section to the list of the task*/
						pipTask.getCriticalSections().add(newCS);
					}
				}

			}
			pip.getTasks().add(pipTask);
		}

		/* Sort the list*/
		ECollections.sort(pip.getTasks(), new PriorityComparator());

		/**/
		return pip;
	}

	@Override
	public String getNodeName() 
	{
		return "srl90a01.impl.Srl90a01";
	}

	@Override
	public void update(Node node) {}

	@Override
	public boolean isEnable() 
	{
		return this.enableCreate;
	}

}
